'use strict';

const axios = require('axios');
const { logger } = require('ee-core/log');
const { exec } = require('child_process');
const { shell, app: electronApp } = require('electron');

const { ticketService } = require('../service/ticket');
const { protocolService } = require('../service/protocol');
const { configService } = require('../service/config');
const { computerService } = require('../service/computer');
const { windowService } = require('../service/window');
const DesCrypto = require("../utils/DesCrypto.js");
const { Notification } = require('electron');
const { homeService } = require("../service/home.js");
const { getMainWindow } = require("ee-core/electron");
/**
 * example
 * @class
 */
class SystemController {
    cookie = null;
    eap5Host = configService.get('eap5Host');
    ssoHost = configService.get('ssoHost');
    eap2Host = configService.get("eap2Host");
    mailHost = configService.get("mailHost");
    //取eap5票据的通用url
    eap5GeneralTicketUrl = `${this.eap2Host}/eap/xtgn/xtsy/sy/dbxx.flow`
    mailMonitoringID = null
    //系统通知
    notification = new Notification({
        icon: './assets/icon.png',
    });
    constructor() {
        this.notification.on('click', (data) => {
            getMainWindow().show();
            this.openMail();
        });
    }
    async login({ userName, password }, event) {
        let result = await ticketService.login(userName, password)
        configService.set('userName', userName);
        if (!result.success) {
            if (/(.*)\（(\d+)\）$/.test(result.message) && !result.message.includes("密码")) {
                result.reg = true;
                try {
                    result.regUrl = await computerService.getRegComputerUrl(userName, password, result.message)
                } catch (error) {
                    result.message = result.message + "," + error.message;
                }
            }
            else if (/(.*)\（(\d+)\）$/.test(result.message) && result.message.includes("密码")) { //密码错误的提示
                const regex = /^([\u4e00-\u9fa5，]+)（(\d+)）$/;
                const match = result.message.match(regex);
                if (match) {
                    let errMsg = match[1];    // "未授权电脑，已授权网络环境"
                    let code = match[2];    // "10001"
                    result.message = errMsg;
                    result.code = code;
                }
            }
            return result;
        }
        //result.ticket = await ticketService.getNewTicket(this.eap5GeneralTicketUrl)
        //登录邮件
        this.loginMail()
        
        let ticket = await ticketService.getNewTicket(this.eap5GeneralTicketUrl)
        let ssoUrl = `${this.ssoHost}/ssoAuth/loginValidate?ticket=${ticket}&service=${encodeURIComponent(this.eap5GeneralTicketUrl)}`
        //后台打开sso地址,让浏览器写入cookie,这样浏览器在访问其他需要经过sso认证的地址时,就可以直接访问了,如打开eap2的地址
        homeService.createTab(ssoUrl, false,false,false,true)
        return result
    }

    async loginMail() {
        let result = await ticketService.loginMail();
        if (result.success) {
            this.mailMonitoring();
        }
    }

    // 监控邮件
    async mailMonitoring() {
        let userInfo = await this.getUserInfo();
        this.mailMonitoringID = setInterval(async () => {
            let url = `${this.mailHost}/webmail/module/mail.do?method=getUnreadMailInfo`;
            let result = await axios.get(url, {
                headers: {
                    'Cookie': userInfo.mailCookie
                }
            })
            this.mailReminder(result.data);
        }, 60000);//1分钟一次 
    }

    // 邮件提醒
    mailReminder(data) {
        if (data.TSL1count == 0) {
            this.notification.close();
            return;
        }
        this.notification.title = `${data.subject}`
        this.notification.body = `${data.currentLoginNum} ${data.sender}/${data.senderName} ${data.sendTime}`
        // new Notification({
        //     title: `${data.subject}`,
        //     body: `${data.currentLoginNum} ${data.sender}/${data.senderName} ${data.sendTime}`,
        //     //icon: './assets/icon.png',
        //     // hasReply: true,
        //     // replyPlaceholder: "replyPlaceholder",
        //     // closeButtonText: "closeButtonText",
        // });


        this.notification.show();
    }

    async getloginapi({userName, password}) {
        return  ticketService.getloginapi(userName, password);
    }
    //网页登录
    async webLogin({ userName, password }, event) {
        try {
            try {
                let key = "15FF3426-3ACD-4E00-7BA7-ABB6573F1F62";
                password = DesCrypto.decrypt(password, key);
            } catch (decryptError) {
                logger.error("webLogin decrypt error for user:", userName, "error:", decryptError.message);
                return {
                    success: false,
                    message: "密码解密失败",
                };
            }
            const result = await this.login({ userName, password }, event);
            if (result.success) {
                protocolService.webLoginSuccess(result)
            }
            return result;

        } catch (error) {
            logger.error("webLogin error:", error.message);
            return {
                success: false,
                message: error.message || "登录过程发生错误",
            };
        }
    }

    //网页退出
    async webLogout(args, event) {
        try {

            await this.logout();
            protocolService.webLogoutSuccess()
            return {
                success: true,
                message: "Logout successful",
            };

        } catch (error) {
            // 统一错误处理
            logger.error("webLogin error:", error.message);
            return {
                success: false,
                message: error.message || "Error",
            };
        }
    }

    //退出
    async logout(args, event) {
        await ticketService.logout();
        if (this.mailMonitoringID) {
            clearInterval(this.mailMonitoringID);
            this.mailMonitoringID = null;
        }
        this.openChrome({ url: `${this.ssoHost}/ssoAuth/logout?service=http://eap2.fdauto.com/eap/auth/login.flow` });
    }

    //获取用户信息
    async getUserInfo() {
        return ticketService.getUserInfo();
    }

    async openMain11111111() {
        const userInfo = await ticketService.getUserInfo();
        //`http://eap2.fdauto.com/eap/xtgn/xtsy/sy/sy.flow` 
        //`${this.eap5Host}/hiroute/entereap.html?pn=fdszh/0000221`   
        //"https://e52.hieap.cn/main.html?pn=fdszh/0000221";
        //http://eap.fdauto.com/bws/system/xtgn/xtzy/zy1-query/bizFunction.open.bws
        let mainUrl = `${this.eap5Host}/main.html?pn=fdszh/0000221&fromEap2=true`
        //取eap5的票据时要用这个通用的service:http://eap2.fdauto.com/eap/rlzy/rsgl/ygda/ygda.flow,用这个通用service取的得票据要加fromEap2=true
        const ticket = await ticketService.getNewTicket(this.eap5GeneralTicketUrl);
        if (ticket) {
            let url = `${this.ssoHost}/ssoAuth/loginValidate?ticket=${ticket}&service=${encodeURIComponent(mainUrl)}`
            return {
                success: true,
                url
            };
        }
        return {
            success: false
        };
    }


    //打开主页
    async openMain() {
        const ticket = await ticketService.getNewTicket(this.eap5GeneralTicketUrl);
        if (ticket) {
            const userInfo = await ticketService.getUserInfo(); //&${userInfo.cookie}
            const url = `${this.eap5Host}/hiroute/entereap.html?pn=fdszh/0000221&${userInfo.cookie}&ticket=${ticket}`  //https://e52.hieap.cn/index.html?pn=fdszh/0000221&ticket=ST-128132-9XykBM45ckLaQ7cEafxe-cas
            //  const url = `https://e52.hieap.cn/main.html?pn=fdszh/0000221&ticket=${ticket}`
            // await this.openChrome({ url, windowName })
            return {
                success: true,
                url
            };
        }
        return {
            success: false
        };

    }

    async openMail() {
        let url = `${this.mailHost}/webmail/index.do?osName=windows`;
        let ticket = await ticketService.getNewTicket(url);
        let ssoUrl = `http://sso.fdauto.com/ssoAuth/loginValidate?service=${encodeURIComponent(url)}&ticket=${ticket}`;
        homeService.createTab(ssoUrl);
    }

    // async getUnreadMailInfo() {
    //     let url = "http://fdmail.fdauto.com:8003/webmail/module/mail.do?method=getUnreadMailInfo";
    //     const ticket = await ticketService.getNewTicket(url);
    //     if (!ticket)
    //         return {
    //             success: false
    //         };
    //     url = `${url}&ticket=${ticket}`
    //     let userInfo = await ticketService.getUserInfo();
    //     let cookie = `${userInfo.cookie};=${ticket}`
    //     let res = await axios.get(url, {
    //         headers: {
    //             'Cookie': cookie
    //         }
    //     })
    //     return res;
    // }

    //打开默认浏览器
    async openChrome({ url, windowName = "fdauto" }, event) {

        console.log(url)
        shell.openExternal(url)
        return;

        const platform = process.platform;
        let command = '';

        // 根据不同平台选择不同的命令
        if (platform === 'win32') {
            // Windows - Chrome
            command = `"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"  --new-window  ${url}`; // --new-window  --window-name=${windowName}  --incognito
        } else if (platform === 'darwin') {
            // macOS - Chrome
            command = `open -na "Google Chrome" --args " ${url}`;
        } else {
            // Linux - Chrome
            command = `google-chrome " ${url}`;
        }
        console.log(command)
        // 执行命令
        exec(command, (error, stdout, stderr) => {
            if (error) {
                console.error(`执行错误: ${error}`);
                // 失败时回退到普通打开方式
                shell.openExternal(url);
                return;
            }
            console.log(`stdout: ${stdout}`);
            console.error(`stderr: ${stderr}`);
        });
    }



    getVersion() {
        const version = electronApp.getVersion();
        return version;
    }
    getConfig(key) {
        return configService.get(key);
    }

    /**
     * Open a new window
     */
    createWindow(args) {
        const wcid = windowService.createWindow(args);
        return wcid;
    }

    exitApp() {
        electronApp.quit();
    }
}
SystemController.toString = () => '[class SystemController]';

module.exports = SystemController; 